cc.Class({
    extends: cc.Component,

    properties: {
        isReContent: true,
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad() {
        this.reConnectTimes = 1
    },

    start() {

    },

    init() {
        let self = this;
        self.wlddMain = self.node.getComponent("wlddMain");
        self.lobbyNet = self.wlddMain.lobbyNet;
        self.lobbyMain = self.wlddMain.lobbyMain;
        let serverIp = self.wlddMain.lobbyMain.configJson.serverIp;
        let port_wldd = self.wlddMain.lobbyMain.configJson.port_wldd;
        // self.lobbyNet.isReContent = false; //关闭大厅自动重连
        // self.lobbyNet.onDestroy(); //断开大厅连接
        self.socket = new WebSocket(`ws://${serverIp}:${port_wldd}`);
        self.socket.onopen = () => {
            self.lobbyMain.gameContent.gameLoading.active = false;
            console.log('🚀美人鱼服务器连接成功');
            let message = {
                action: "clientId",
                playerId: self.wlddMain.playerInfo.playerId,
            }
            self.socket.send(JSON.stringify(message));

        };
        self.socket.onmessage = (event) => {
            const data = JSON.parse(event.data);
            switch (data.action) {
                case "spinResponse":  // 登录
                    console.log(data);
                    self.wlddMain.spinResponse(data);
                    break;
                default:
                    break;
            }
        };
        self.socket.onerror = (error) => {
            console.error('与服务端连接报错:', error);
        };
        self.socket.onclose = () => {
            console.log('与美人鱼服务端连接断开');
            if (self.lobbyMain) {
                self.lobbyMain.openLoading("reconnecting");
            }
            if (self.isReContent) {
                reconnectTimeout = setTimeout(() => {
                    console.log('第 ' + this.reConnectTimes + ' 次尝试重新连接...');
                    this.reConnectTimes++;
                    self.onDestroy();
                    self.init();
                }, 5000);
            }
        };
    },

    sendMessage(message) {
        this.socket.send(JSON.stringify(message));
    },

    onDestroy() {
        if (this.socket) {
            this.socket.close();
        }
    },

});
